/**
 * Copyright 2023 Inc.
 **/
package com.myz.service.ribbon.core;

import com.netflix.client.DefaultLoadBalancerRetryHandler;
import com.netflix.client.RetryHandler;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.LoadBalancerBuilder;
import com.netflix.loadbalancer.LoadBalancerStats;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.reactive.LoadBalancerCommand;
import rx.Observable;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * @author maoyz0621 on 2023/3/30
 * @version v1.0
 */
public class LoadBalancer {

    private final ILoadBalancer loadBalancer;

    private final RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler();

    public LoadBalancer(List<Server> serverList) {
        this.loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(serverList);
    }

    public String call(final String path) {
        return LoadBalancerCommand.<String>builder()
                // 负载均衡工具
                .withLoadBalancer(loadBalancer)
                // 重试策略
                .withRetryHandler(retryHandler)
                .build()
                .submit(server -> {
                    URL url;
                    try {
                        url = new URL("http://" + server.getHost() + ":" + server.getPort() + path);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        return Observable.just(connection.getResponseMessage() + connection.getResponseCode());
                    } catch (IOException e) {
                        e.printStackTrace();
                        return Observable.error(e);
                    }

                })
                .toBlocking()
                .first();
    }

    public LoadBalancerStats getLoadBalancerStats() {
        return ((BaseLoadBalancer) loadBalancer).getLoadBalancerStats();
    }

    public static void main(String[] args) {

    }
}